package org.example.novel.utlis;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 获取请求参数工具类
 */
public class RequestUtils {


    /**
     * 根据名称从请求头或cookie里拿到对应的值
     * @param name
     * @return
     */
    public static String getValueByRequestHandersAndCookies(String name){

        HttpServletRequest request = getRequest();

        String token = request.getHeader(name);

        if (token!=null) return token;

        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if (cookie!=null) if (cookie.getName().equals(name)) return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 获取名称获取token
     * @param name
     * @return
     */
    public static String getToken(String name){
        return getValueByRequestHandersAndCookies(name);
    }

    /**
     * 请求的json数据转换成map
     * @return
     */
    public static HashMap<String,Object> parseMapByJson(){
        HashMap<String,Object> hashMap = null;
        try {

            hashMap = new ObjectMapper().readValue(getRequest().getInputStream(), new TypeReference<HashMap<String,Object>>(){});

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return hashMap;
    }

    /**
     * 请求的json数据转换成class
     * @param tClass
     * @return
     * @param <T>
     */
    public static <T> T parseObjByJson(Class<T> tClass){

        T t = null;
        try {

            t = new ObjectMapper().readValue(getRequest().getInputStream(), tClass);

        } catch (IOException e) {

            throw new RuntimeException("数据转换异常");

        }

        return t;
    }

    /**
     * 从请求上下文中获取请求对象
     * @return
     */
    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

}
